#!/bin/sh
###############################################################################
##  Author    : xuezhoyi
##  Name      : edw_batch_start.sh
##  Functions : 
##  Purpose   : 
##  Revisions or Comments
##  VER        DATE        AUTHOR           DESCRIPTION
##---------  ----------  ---------------  ------------------------------------ 
##  1.0      2017-05-22  xuezhouyi        1. CREATED THIS SHELL.
###############################################################################

. ${0%`basename ${0}`}edw_parm.sh
. ${0%`basename ${0}`}edw_func.sh

function USAGE(){
    echo -e "\nHow to use this shell script!"
    echo -e '\n${V_SHELL_HOME}/edw_batch_start.sh 20170101'
}

# Check variable
if [[ -z ${1} ]];then
    USAGE
    exit 1
fi

# Define basic parm
V_SCRIPT_NAME=$(basename ${0} | cut -d'.' -f1)
V_OUT_LOGS="${V_SHELL_LOGS}/${V_SCRIPT_NAME}_${V_TIME_STAMP}_$$.log"

# Define the output flow
exec 4>&1               # screen output
exec 3>>${V_OUT_LOGS}   # script output
exec 2>&3               # error output
exec 1>&3               # standard output
echo -e "[Begin: $(date +%F) $(date +%T)]"

# Get parm
V_DATA_DATE=${1}
echo -e "\nToday batch date is ${V_DATA_DATE}."

# Update end time
V_QUERY="UPDATE ETL.EDW_BATCH_CONTROL SET END_TIME = NOW() WHERE DATA_DATE = '${V_DATA_DATE}';"
${V_RUN_MYSQL} -q "${V_QUERY}"
if [[ $? -eq 0 ]];then
    echo -e "\nSuccess to end batch."
else
    echo -e "\nCan not update END_TIME."
    echo -e "\n${V_QUERY}"
    exit 1
fi

# For rerun
V_NEXT_DATA_DATE=$(GET_NEXT_DATE ${V_DATA_DATE})
V_QUERY="DELETE FROM ETL.EDW_BATCH_CONTROL WHERE DATA_DATE = '${V_NEXT_DATA_DATE}';"
${V_RUN_MYSQL} -q "${V_QUERY}"
if [[ $? -eq 0 ]];then
    echo -e "\nSuccess to initinal next batch ${V_NEXT_DATA_DATE}."
else
    echo -e "\nCan not prepare next batch."
    echo -e "\n${V_QUERY}"
    exit 1
fi

# Insert the next batch records
V_QUERY="DELETE FROM ETL.EDW_BATCH_CONTROL WHERE DATA_DATE = '${V_NEXT_DATA_DATE}';"
${V_RUN_MYSQL} -q "${V_QUERY}"
V_QUERY="INSERT INTO ETL.EDW_BATCH_CONTROL(DATA_DATE,ALL_ORG) VALUES('${V_NEXT_DATA_DATE}','Y');"
${V_RUN_MYSQL} -q "${V_QUERY}"
if [[ $? -eq 0 ]];then
    echo -e "\nSuccess to prepare next batch ${V_NEXT_DATA_DATE}."
else
    echo -e "\nCan not prepare next batch."
    echo -e "\n${V_QUERY}"
    exit 1
fi

echo -e "\n[End: $(date +%F) $(date +%T)]"
echo 0 >&4
exit 0
